package com.mk.community.modules.bbs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.community.common.api.CommonPage;
import com.mk.community.modules.bbs.dto.DiscussPostVo;
import com.mk.community.modules.bbs.mapper.DiscussPostMapper;
import com.mk.community.modules.bbs.model.DiscussPost;
import com.mk.community.modules.bbs.model.User;
import com.mk.community.modules.bbs.service.DiscussPostService;
import com.mk.community.modules.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MagicKong
 * @since 2021-09-27
 */
@Service
public class DiscussPostServiceImpl extends ServiceImpl<DiscussPostMapper, DiscussPost> implements DiscussPostService {

    @Autowired
    private UserService userService;

    @Override
    public CommonPage<DiscussPostVo> listDiscussPost(Integer userId, long current, long size) {
        Page<DiscussPost> page = new Page<>(current, size);
        QueryWrapper<DiscussPost> wrapper = new QueryWrapper<>();
        // 构造动态 sql
        // 1. userId = 0 查所有, userId != 0 查指定用户的帖子
        if (userId != 0) {
            wrapper.eq("user_id", userId);
        }
        // 2. 过滤拉黑的帖子
        wrapper.ne("status", 2);
        // 3. 根据类型逆序排序
        wrapper.orderByDesc("type");
        // 4. 根据创建时间逆序排序
        wrapper.orderByDesc("create_time");
        this.page(page, wrapper);
        // 5. 根据 userId 封装 User 对象
        List<DiscussPostVo> collect = page.getRecords().stream().map(discussPost -> {
            DiscussPostVo discussPostVo = BeanUtil.copyProperties(discussPost, DiscussPostVo.class);
            User byId = userService.getById(discussPost.getUserId());
            discussPostVo.setUser(byId);
            return discussPostVo;
        }).collect(Collectors.toList());
        Page<DiscussPostVo> pageResult = new Page<>();
        BeanUtil.copyProperties(page, pageResult, "records");
        pageResult.setRecords(collect);
        return CommonPage.restPage(pageResult);
    }
}
